package net.sf.rose.business.action;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.rose.business.bean.base.DownloadFileBean;
import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;
import net.sf.rose.web.spring.servlet.handler.FormConvert;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author fengjian
 * @since 2014/07/04
 */
@Controller
public class Download {

	final static int MAX_MENO_SIZE = 6 * 1024;// 设置文件缓存放置在内存中的临界值为 6K，超过的缓存在磁盘上
	final static long MAX_SIZE = 6 * 1024 * 1024;// 设置上传文件最大为 3M
	public final static String TEMP_FILES = "temp_files";
	public final static String DOWNLOAD_FILE = "download_file";
	public final static String DOWNLOAD_FILE_NAME = "download_file_name";

	@RequestMapping("/upload/view.html")
	public ModelAndView uploadView(HttpServletRequest request) {
		FormConvert form = new FormConvert();
		ModelAndView mav = new ModelAndView("download/upload_view", form.convertRequest(request));
		return mav;
	}

	@RequestMapping("/upload/do.html")
	public ModelAndView uploadDo(HttpServletRequest request) {
		Map<String, DownloadFileBean> map = new HashMap<String, DownloadFileBean>();
		try {
			String tempath = System.getenv("TEMP");
			if (tempath == null) {
				tempath = "c:/";
			}
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 保存在内存中的临界值
			factory.setSizeThreshold(MAX_MENO_SIZE);
			factory.setRepository(new java.io.File(tempath));
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(MAX_SIZE);
			String key = null;
			String val = null;
			FileItem item = null;
			java.util.Iterator<?> it = upload.parseRequest(request).iterator();
			while (it.hasNext()) {
				item = (FileItem) it.next();
				if (item.isFormField()) {
					key = item.getFieldName();
					val = item.getString("UTF-8").trim();
					// files.file[0],files.name[0]
					int s = key.indexOf('[');
					int e = key.indexOf(']');
					if (s != -1) {
						String index = key.substring(s, e);
						DownloadFileBean download = map.get(index);
						if (download == null) {
							download = new DownloadFileBean();
							map.put(index, download);
						}
						download.setIndex(index);
						if (!val.equals("")) {
							download.setName(val);
						}
					} else {
						if (!val.equals("")) {
							DownloadFileBean download = new DownloadFileBean();
							download.setName(key);
							download.setFileName(val);
							map.put(key, download);
						}
					}
				} else {
					if (!item.getName().equals("")) {
						key = item.getFieldName();// 字段名
						String name = item.getName();// 文件名
						name = name.substring(name.lastIndexOf('\\') + 1, name.length());
						int s = key.indexOf('[');
						int e = key.indexOf(']');
						DownloadFileBean download = null;
						if (s != -1) {
							String index = key.substring(s, e);
							download = map.get(index);
							if (download == null) {
								download = new DownloadFileBean();
								map.put(index, download);
							}
						}
						download.setFileName(name);
						download.setData(item);
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		HttpSession s = request.getSession();
		s.setAttribute(TEMP_FILES, map);
		ModelAndView mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	@RequestMapping("/download.html")
	public ModelAndView downloadView(HttpServletRequest request, HttpServletResponse response) {
		Object obj = request.getAttribute(DOWNLOAD_FILE);
		if (obj == null) {
			throw new SystemException("Action参数缺失！，" + DOWNLOAD_FILE + "不能为空。", SystemErrorCode.PRARAMTER_LOST_ERROR);
		}
		File file = (File) obj;
		String filename = null;
		obj = request.getAttribute(DOWNLOAD_FILE_NAME);
		if (obj != null) {
			filename = obj.toString();
		} else {
			filename = file.getName();
		}
		try {
			InputStream in = new FileInputStream(file);
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				bout.write(buf, 0, len);
			}
			in.close();
			
			response.reset();
			// String fileName = URLEncoder.encode(filename, "UTF-8");
			String fileName = new String(filename.getBytes(),"ISO8859-1");
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream; charset=UTF-8");
			toClient.write(bout.toByteArray());
			toClient.flush();
			toClient.close();
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
